package cn.wangxl.vertx.starter.web;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;

/**
 * mime选择
 */
public class MimeRouterVerticle extends AbstractVerticle {

  @Override
  public void start(Future<Void> startFuture){

    Vertx vertx = Vertx.vertx();

    HttpServer server = vertx.createHttpServer();

    Router router = Router.router(vertx);

    // 指定请求体类型
    Route route1 = router.route().consumes("text/html").handler(routingContext -> {

      HttpServerResponse response = routingContext.response();

      response.end("text/html");
    });

//    // 指定通配请求体类型
//    Route route2 = router.route().consumes("application/*").handler(routingContext -> {
//
//      HttpServerResponse response = routingContext.response();
//
//      response.end(routingContext.request().getHeader("Content-Type"));
//    });

    router.route().produces("application/json").handler(routingContext -> {

      HttpServerResponse response = routingContext.response();
      response.putHeader("content-type", "application/json");
      response.end("{id:100}");

    });

    server.requestHandler(router).listen(8888, http -> {
      if (http.succeeded()) {
        startFuture.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startFuture.fail(http.cause());
      }
    });
  }


  private Future<Void> startHttpServer() {
    Future<Void> future = Future.future();
    // (...)
    return future;
  }


  public static void main(String[] args) throws Exception {
    new MimeRouterVerticle().start(Future.future());
  }
}
